﻿using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Linq;
using System.Web;

namespace AuroraPlugin
{
    public partial class PluginAuth : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request["userkey"]))
            {
                Response.Write("{\"ResultCode\":\"##resultcode##\"}".Replace("##resultcode##", "-1"));
                return;
            }
            Guid guid;
            if (!Guid.TryParse(Request["userkey"], out guid))
            {
                Response.Write("{\"ResultCode\":\"##resultcode##\"}".Replace("##resultcode##", "-1"));
                return;
            }
            var a = Database.db.Queryable<AP_UserKeys>().Where(it => it.guid == guid).ToList();
            if (a.Count <= 0)
            {
                Response.Write("{\"ResultCode\":\"##resultcode##\"}".Replace("##resultcode##", "0"));
                return;
            }
            if (a.First().isbanned)
            {
                Response.Write("{\"ResultCode\":\"##resultcode##\"}".Replace("##resultcode##", "2"));
                return;
            }
            if (a.First().machinecode.Split('|')[1] != HttpContext.Current.Request.UserHostAddress)
            {
                a.First().isbanned = true;
                Database.db.Updateable(a.First()).ExecuteCommand();
                Response.Write("{\"ResultCode\":\"##resultcode##\"}".Replace("##resultcode##", "2"));
                return;
            }
            JObject jObject = new JObject();
            jObject.Add("ResultCode", "1");
            foreach (string b in a.First().plugins.Split('|'))
            {
                if (b == "0") continue;
                ISugarQueryable<AP_Plugins> c = Database.db.Queryable<AP_Plugins>().Where(it => it.id == ushort.Parse(b));
                if (c.Count() <= 0)
                {
                    continue;
                }
                if (!c.First().isdrm)
                {
                    jObject.Add(b, c.First().name + "|" + c.First().achikey + "|" + c.First().filemd5 + "|nodrm");
                }
                else jObject.Add(b, c.First().name + "|" + c.First().achikey + "|" + c.First().filemd5 + "|drm");
            }
            Response.Write(jObject.ToString());
        }
    }
}